
let query = require("../model/connect")


const express = require("express");
let router = express.Router();
const fs = require("fs");
const path = require("path");
let nums = 0;

// 1.获取景区列表getdataList
// 2.更新点赞数量updateLike
// 3.获取景区详细信息getJourneyDetail
// 4.更新景区评价updateRating
// 5.获取景点详细信息getScenicDetail

// 获取景区列表

router.get("/getdataList", async (req, res) => {
    // console.log(req.headers);
    try {
        let { uid, p } = req.query;
        // console.log(p);
        let perpage = 4;
        // 获取景区名字，景区介绍，景区地点，景区封面，景区游玩时间，点赞数量
        let result = await query(`SELECT * FROM scenery A LIMIT ${(p-1) * perpage},${perpage}`);

        for (let i = 0; i < result.length; i++) {
            // 统计 点赞数量
            let likeArr = await query(`SELECT * FROM scenery_likes WHERE sid=${result[i].id}`);
            result[i].like = likeArr.length;  // 点赞的数量
            let str = `SELECT * FROM scenery_likes WHERE uid=${uid} AND sid=${result[i].id}`;
            let likeResult = await query(str);
            if (likeResult.length === 0) {
                result[i].islike = false;
            } else {
                result[i].islike = true;
            }
        }
        // console.log(result);
        res.json({
            // info: "返还result成功",
            status: 1,
            result
        })
    } catch (err) {
        res.json({
            // info: "",
            status: 0,
        })
    }
})


router.put("/updateLike", async (req, res) => {
    try {
        let { uid, sid,op } = req.body;
        // 如果点赞了，可以查询到 ，取消点赞 （删除该数据）
        // 如果没有点赞 ，不能查询到信息，记录点赞 （添加该点赞信息）
        let str = `SELECT * FROM scenery_likes WHERE uid=${uid} AND sid=${sid}`;
        let result = await query(`SELECT * FROM scenery_likes WHERE sid=${sid} AND uid=${uid}`);
        let lengthresult = await query(`SELECT * FROM scenery_likes WHERE sid=${sid}`);
        let likenum = lengthresult.length;
        let likeResult = await query(str);
        let islike;
        if (likeResult.length === 0) {
             islike = false;
        } else {
             islike = true;
        }
       if(op){
        if (result.length === 0) {
            // 没有点赞
            let res2 = await query(`INSERT INTO scenery_likes(uid,sid) VALUES(${uid},${sid})`);
            likenum++;
            res.json({
                // info: "更新成功",
                likenum,
                status: 1,
                islike: true
            })
        }
        else {
            let res3 = await query(`DELETE FROM scenery_likes WHERE uid=${uid} AND sid=${sid}`);
            likenum--;
            res.json({
                // info: "",
                likenum,
                status: 1,
                islike: false
            })
        }
        
       }
       else{
        res.json({
            status:1,
            likenum,
            islike
           })
       }
   
     

    } catch (err) {
        // console.log(err);
        res.json({
            // info: "",
            status: 0,

        })
    }

})

router.get("/getJourneyDetail", async (req, res) => {
    try {
        // 获取景区信息
        let nums = 0;
        let { uid, sid } = req.query;
        // 获取景区名字，景区游玩时间，景区游玩计划，景区图片，景区评分
        let result1 = await query(`SELECT scenery.id,scenery.title,scenery.duration FROM scenery  WHERE scenery.id=${sid}`);
        //从scenery_imgs表中获取图片 
        let result2 = await query(`SELECT imgurl FROM scenery_imgs WHERE scenery_imgs.sid=${sid}`)
        result1[0].imgs = result2.map(item => item.imgurl);
        //从scenery_plan表中获取游玩计划 
        let result3 = await query(`SELECT scenery_plan.time,scenery_plan.detail FROM scenery_plan WHERE scenery_plan.sid=${sid}`)
        result1[0].plans = result3.map(item => (item.time,item.detail));
        //从scenery_plan表中获取景区评分和评分数量
        let ratingArr = await query(`SELECT scenery_rating.uid,scenery_rating.rating FROM scenery_rating WHERE scenery_rating.sid=${sid}`)
        let ratingnum = ratingArr.length;
        ratingArr.map(item =>{
            nums+=item.rating
        }); 
        result1[0].ratingnum=ratingnum;
        result1[0].rating=nums/ratingnum;
        // 从scenery_rating表中获取该用户是否评分，false为未评分，true为已评分
        let israting=await query(`SELECT * FROM scenery_rating WHERE scenery_rating.uid=${uid} AND scenery_rating.sid=${sid}`)
        if(israting.length==0){
            result1[0].israting=false;
        }
        else{
            result1[0].israting=true;
        }
        // 从scenery_part表中获取景点信息
        let result4=await query(`SELECT scenery_part.title,scenery_part.iconurl,scenery_part.title,scenery_part.id FROM scenery_part WHERE scenery_part.sid=${sid}`)
        result1[0].scenic = result4.map(item =>({title:item.title,iconurl:item.iconurl,id:item.id}))
        // console.log(result1);

        res.json({
            // info: "返还result成功",
            status: 1,
            result:result1[0]
        })
    } catch (err) {
        // console.log(err);
        res.json({
            // info: "",
            status: 0,
        })
    }
})

router.put("/updateRating", async (req, res) => {
    try {
        let { uid, sid, rating } = req.body;
        let result5 = await query(`SELECT * FROM scenery_rating WHERE scenery_rating.sid=${sid} AND scenery_rating.uid=${uid}`);
        let ratingnum = result5.length;
        if (result5.length === 0) {
            // 没有评分
            let res2 = await query(`INSERT INTO scenery_rating(uid,sid,rating) VALUES(${uid},${sid},${rating})`);
            ratingnum++;
            res.json({
                // info: "更新成功",
                ratingnum,
                israting:false,
                status: 1
            })
        }
        else {
            let res3 = await query(`DELETE  FROM scenery_rating WHERE uid=${uid} AND sid=${sid} AND rating=${rating}`);
            ratingnum--;
            res.json({
                israting:true,
                status:2
            })
        }

    } catch (err) {
        res.json({
            // info: "",
            status: 0,
        })
    }

})

router.get("/getScenicDetail", async (req, res) => {
    try {
        let { id } = req.query;
        let result6 = await query(`SELECT title,imgurl,introduce FROM scenery_part WHERE scenery_part.id=${id}`)
        // console.log(result6);
        res.json({
            result:result6[0],
            status: 1
        })
    } catch(err){
        // console.log(err);
        res.json({
            // info:"获取失败"
            status: 0
        })
    }
})

router.get("/getcollect",async(req,res)=>{
    try{
        let {uid} = req.query
        let str = `SELECT scenery_likes.sid  FROM scenery_likes WHERE uid=${uid}`;
        let ownarr = [];
        let Result = await query(str);
        for(i=0;i<Result.length;i++){
            let result1 = await query(`SELECT * FROM scenery A WHERE id=${Result[i].sid}`);
            ownarr.push(result1[0])
        }
        res.json({
            status:1,
            result:ownarr
        })

    }catch(err){
        // console.log(err);
        res.json({
            status:0, 
        })
    }

   
})

module.exports = router;